//
//  DPBrowserUser.m
//  SimpleBrowser
//
//  Created by Ofri Wolfus on 30/03/07.
//  Copyright 2007 Ofri Wolfus. All rights reserved.
//

#import "DPBrowserUser.h"


@implementation DPBrowserUser

- (id)init {
	if ((self = [super init])) {
		browser = [[DPTestSubject anyChildNamed:@"SimpleBrowser.fsBrowser"] retain];
		columnIndex = 0U;
		rowIndex = 0U;
	}
	
	return self;
}

- (void)dealloc {
	[browser release];
	[super dealloc];
}

/*
 * This method gets periodically invoked by UITestingKit in order to perform
 * user actions.
 * In our case we'll select a new row in the browser each time, and once we get
 * to the end of a column, we'll go to the next one if one is available.
 * When we're done we should simply return NO and UITestingKit will proceed to the
 * next user object(s).
 */
- (BOOL)performNextAction {
	// Get all columns in our browser
	NSArray *columns = [browser valueForAttribute:NSAccessibilityColumnsAttribute];
	// Each column is actually a scroll view containing a list of rows
	DPUIElement *scrollView = [columns objectAtIndex:columnIndex];
	unsigned rowCount = 0U;
	
	// Find the list element in this scroll view
	// TODO: Incorporate HOM to UITestingKit to make these things easier
	NSEnumerator *childs = [[scrollView children] objectEnumerator];
	DPUIElement *list;
	
	while ((list = [childs nextObject]))
		if ([[list role] isEqualToString:NSAccessibilityListRole])
			break;
	
	// Now that we found the list (hopefully), we'll walk its rows one by one
	if (list) {
		NSArray *rows = [list children];
		rowCount = [rows count];
		
		if (rowCount > 0U) {
			// It's possible to select more than one row, but for our example it'll do
			[list setValue:[NSArray arrayWithObject:[rows objectAtIndex:rowIndex]]
			  forAttribute:NSAccessibilitySelectedChildrenAttribute];
			++rowIndex;
		}
	}
	
	// Have we finished this column?
	if (rowIndex + 1U >= rowCount) {
		++columnIndex;
		rowIndex = 0U;
	}
	
	return columnIndex < [browser valueCountForAttribute:NSAccessibilityColumnsAttribute]
		&& columnIndex < 5;	// Assume everything is fine after 5 columns
}

@end
